<?php
include("include/conn.php");
require('include/Smarty/libs/Smarty.class.php');


$billBookId   = isset($_REQUEST['billBookId']) ? $_REQUEST['billBookId'] : 0;
$partyId     = 0;
$isEdit      = 0;
$billBookNo  = 1;
$msg         = isset($_GET['msg']) ? $_GET['msg'] : "";
$queryField  = "";
$queryValue  = "";
$billDate    = "";
$party       = array();
$billBookArr = array();
$billBookRes = 0;
//Cancel:Start

if(isset($_POST['cancelBtn']))
{
  header("Location:billBookList.php");
  exit();
}
//Cancel:End
//echo "Test : ".$billBookId."<br>";
if(isset($_POST['billBookAddBtn']))
{ 
  if($billBookId > 0)
  { 
    $billBook = "SELECT billNo FROM billbook
                  WHERE billBookId != ".$_POST['billBookId']."
                    AND billNo = ".$_POST['billBookNo']."
                    AND DATE_FORMAT(CURDATE(),'%Y-%m') = '".$_POST['curDateYear']."-".$_POST['curDateMonth']."'";
    $billBookRes = mysql_query($billBook);

    //$billBook = "SELECT billNo FROM billbook WHERE billNo = 94 AND DATE_FORMAT(CURDATE(),'%Y-%m') = (SELECT '".$_POST['curDateYear']."-".$_POST['curDateMonth']."' + INTERVAL -1 MONTH)";
    //$billBookRes = mysql_query($billBook);
    if(mysql_num_rows($billBookRes) > 0)
      $billAlreadyExist = 1;
    else
    {
      $billAlreadyExist = 0;
     //$queryField = " billNo = ".$_POST['billBookNo'].",";
    }
    $totalFine   = (isset($_POST['totFine']) && $_POST['totFine'] > 0) ? $_POST['totFine'] : 0;
    $totalAmount = (isset($_POST['totAmount']) && $_POST['totAmount'] > 0) ? $_POST['totAmount'] : 0;
    if(isset($_POST['partyFine']) && $_POST['partyFine'] > 0)
    {
      $prevFine    = $_POST['partyFine'];
    }
    elseif(isset($_POST['totFine']) && $_POST['totFine'] > 0)
    {
    	$prevFine    = $_POST['totFine'];
    }
    else
    {
    	$prevFine    = 0;
    }
    
    if(isset($_POST['partyAmount']) && $_POST['partyAmount'] > 0)
    {
      $prevAmount    = $_POST['partyAmount'];
    }
    elseif(isset($_POST['totAmount']) && $_POST['totAmount'] > 0)
    {
    	$prevAmount    = $_POST['totAmount'];
    }
    else
    {
    	$prevAmount    = 0;
    }
    $removePrev  = (isset($_POST['removePrev'])) ? 1 : 0;
      
    $updateBillBook = "UPDATE billbook SET partyId       = ".$_POST['party'].", 
                                           billBookDate  = '".$_POST['curDateYear']."-".$_POST['curDateMonth']."-".$_POST['curDateDay']."',
                                           totalFine     = ".round($totalFine).", 
                                           totalAmount   = ".$totalAmount."
                                      WHERE billBookId = ".$_POST['billBookId'];
    $updateBillBookRes = mysql_query($updateBillBook);
    $vepaariBookId = mysql_insert_id();
    
    $updatevepaaribillmaster = "UPDATE vepaaribillmaster
                                   SET partyId = ".$_POST['party'].", vepaariBookDate = '".$_POST['curDateYear']."-".$_POST['curDateMonth']."-".$_POST['curDateDay']."' , totalFine = ".$totalFine.", totalAmount = ".$totalAmount."
                                 WHERE billBookId = ".$billBookId;
    $updatevepaaribillmasterRes = mysql_query($updatevepaaribillmaster);
    
    $deleteBillDetail = "DELETE FROM billbookdetail
                          WHERE billBookId = ".$_POST['billBookId'];
    $deleteBillDetailRes = mysql_query($deleteBillDetail);
    $billBookId = $_POST['billBookId'];
  }
  else
  {
  	$billBook = "SELECT billNo FROM billbook
                  WHERE billNo = ".$_POST['billBookNo']."
                    AND DATE_FORMAT(CURDATE(),'%Y-%m') = '".$_POST['curDateYear']."-".$_POST['curDateMonth']."'";
    $billBookRes = mysql_query($billBook);
    
    $billBook = "SELECT billNo 
                   FROM billbook 
                  WHERE billNo = 100 
                    AND DATE_FORMAT(CURDATE(),'%Y-%m') = 
                                    (SELECT '".$_POST['curDateYear']."-".$_POST['curDateMonth']."' + INTERVAL -1 MONTH)";
    $billBookRes = mysql_query($billBook);
    if(mysql_num_rows($billBookRes) > 0)
      $billAlreadyExist = 1;
    else
    {
      $billAlreadyExist = 0;
      $queryField = "billNo, ";
      $queryValue = $_POST['billBookNo'].", ";
    }
    $updatevepaaribillmaster = "UPDATE vepaaribilldetail
                                   SET billDone = 'Y'
                                 WHERE vepaariBookMasterId IN (SELECT vepaariBookMasterId 
                                                                FROM vepaaribillmaster 
                                                               WHERE partyId = ".$_POST['party'].")";
    $updatevepaaribillmasterRes = mysql_query($updatevepaaribillmaster);
    
    $updatevepaaribilldetail = "UPDATE vepaaribilldetail
                                   SET partyId = '".$_POST['party']."'
                                 WHERE vepaariBookMasterId IN (SELECT vepaariBookMasterId 
                                                                FROM vepaaribillmaster 
                                                               WHERE partyId = ".$_POST['party'].")";
    $updatevepaaribilldetailRes = mysql_query($updatevepaaribilldetail);  
    
    $updatevepaaribilldetail = "UPDATE vepaaribilldetail
                                   SET billBookNo = '".$_POST['billBookNo']."'
                                 WHERE vepaariBookMasterId IN (SELECT vepaariBookMasterId 
                                                                FROM vepaaribillmaster 
                                                               WHERE partyId = ".$_POST['party'].")";
    $updatevepaaribilldetailRes = mysql_query($updatevepaaribilldetail);      
        
    $totalFine   = (isset($_POST['totFine']) && $_POST['totFine'] > 0) ? $_POST['totFine'] : 0;
    $totalAmount = (isset($_POST['totAmount']) && $_POST['totAmount'] > 0) ? $_POST['totAmount'] : 0;
    if(isset($_POST['partyFine']) && $_POST['partyFine'] > 0)
    {
      $prevFine    = $_POST['partyFine'];
    }
    elseif(isset($_POST['totFine']) && $_POST['totFine'] > 0)
    {
    	$prevFine    = $_POST['totFine'];
    }
    else
    {
    	$prevFine    = 0;
    }
    
    if(isset($_POST['partyAmount']) && $_POST['partyAmount'] > 0)
    {
      $prevAmount    = $_POST['partyAmount'];
    }
    elseif(isset($_POST['totAmount']) && $_POST['totAmount'] > 0)
    {
    	$prevAmount    = $_POST['totAmount'];
    }
    else
    {
    	$prevAmount    = 0;
    }    
    $removePrev  = (isset($_POST['removePrev'])) ? 1 : 0;
    
    echo $billBookInsert = "INSERT INTO billbook (".$queryField."partyId, billBookDate, totalFine, totalAmount,showPrev,prevFine,prevAmount)
                       VALUES (".$queryValue."".$_POST['party'].",'".$_POST['curDateYear']."-".$_POST['curDateMonth']."-".$_POST['curDateDay']."',
                               ".$totalFine.",".$totalAmount.",".$removePrev.",".$_POST['fixedPartyFine'].",".$_POST['fixedPartyAmount'].")";
    $billBookInsertRes = mysql_query($billBookInsert);
    $billBookId = mysql_insert_id();

    // Query kept to update previous fine and amount : Starts
    echo $vepaariBookInsert = "INSERT INTO vepaaribillmaster (billNo,partyId,billBookId,vepaariBookDate,totalFine,totalAmount)
                       VALUES (".$queryValue."".$_POST['party'].",".$billBookId.",'".$_POST['curDateYear']."-".$_POST['curDateMonth']."-".$_POST['curDateDay']."',
                               ".$totalFine.",".$totalAmount.")";
    $vepaariBookInsertRes = mysql_query($vepaariBookInsert);
    $vepaariBookId = mysql_insert_id();
  }
  
  $loopCount = 0;
  while($loopCount < count($_POST['particulars']))
  {
    $weight    = ($_POST['weight'][$loopCount] != '') ? $_POST['weight'][$loopCount] : 0;
    $pari      = ($_POST['pari'][$loopCount] != '') ? $_POST['pari'][$loopCount] : 0;
    $netWeight = ($_POST['netWeight'][$loopCount] != '') ? $_POST['netWeight'][$loopCount] : 0;
    $touch     = ($_POST['touch'][$loopCount] != '') ? $_POST['touch'][$loopCount] : 0;
    $waste     = ($_POST['waste'][$loopCount] != '') ? $_POST['waste'][$loopCount] : 0;
    $fine      = ($_POST['fine'][$loopCount] != '') ? $_POST['fine'][$loopCount] : 0;
    $qty       = ($_POST['qty'][$loopCount] != '') ? $_POST['qty'][$loopCount] : 0;
    $labour    = ($_POST['labour'][$loopCount] != '') ? $_POST['labour'][$loopCount] : 0;
    $amount    = ($_POST['amount'][$loopCount] != '') ? $_POST['amount'][$loopCount] : 0;
    
    if($_POST['particulars'][$loopCount] != ''|| $_POST['weight'][$loopCount] != ''|| $_POST['pari'][$loopCount] != ''|| 
       $_POST['netWeight'][$loopCount] != ''|| $_POST['touch'][$loopCount] != ''|| $_POST['waste'][$loopCount] != ''|| 
       $_POST['fine'][$loopCount] != ''|| $_POST['particular'][$loopCount] != ''|| $_POST['qty'][$loopCount] != ''|| 
       $_POST['labour'][$loopCount] != ''|| $_POST['amount'][$loopCount] != '')
    {
      $billBookDetail = "INSERT INTO billbookdetail (billBookId, particulars, weight, pari, netWeight, touch, waste, fine,particular, qty, labour, amount)
                         VALUES (".$billBookId.",'".addslashes($_POST['particulars'][$loopCount])."',".$weight.",".$pari.",
                                 ".$netWeight.",".$touch.",".$waste.",".$fine.",'".addslashes($_POST['particular'][$loopCount])."',".$qty.",
                                 ".$labour.",".$amount.")";
      $billBookDetailRes = mysql_query($billBookDetail);
    }
    $loopCount++;
  }
  
  if($_POST['isEdit'] == 1 && $billAlreadyExist != 1) 
  {
    header("location:billbookList.php");
    exit();
  }
  else if($billAlreadyExist == 1)
  {
    header("location:billBookAdd.php");
  }
  else
  {
  	header("location:billBookAdd.php");
  }	
  

}

if(isset($_GET['billBookId']) && $_GET['billBookId'] > 0)
{
  $isEdit = 1;
  
  $selectParty = "SELECT billBookId,billNo,partyId,billBookDate FROM billbook
                   WHERE billBookId = ".$_GET['billBookId'];
  $selectPartyRes = mysql_query($selectParty);
  $row = mysql_fetch_assoc($selectPartyRes);
  $partyId    = $row['partyId'];
  $billDate   = $row['billBookDate'];
  $billBookId = $row['billBookId'];
  $billBookNo = $row['billNo'];
  
  $selectBill = "SELECT billBookDetailId, billBookId, particulars, weight, pari, netWeight, touch, waste, fine, particular, qty, labour, amount 
                   FROM billbookdetail
                  WHERE billBookId = ".$_GET['billBookId'];
  $selectBillRes = mysql_query($selectBill);
  $a = 0;
  while($billRow = mysql_fetch_assoc($selectBillRes))
  {
    $billBookArr[$a]['id']          = $billRow['billBookDetailId'];
    $billBookArr[$a]['particulars'] = $billRow['particulars'];
    $billBookArr[$a]['weight']      = $billRow['weight'];
    $billBookArr[$a]['pari']        = $billRow['pari'];
    $billBookArr[$a]['netWeight']   = $billRow['netWeight'];
    $billBookArr[$a]['touch']       = $billRow['touch'];
    $billBookArr[$a]['waste']       = $billRow['waste'];
    $billBookArr[$a]['fine']        = $billRow['fine'];
    $billBookArr[$a]['particular']  = $billRow['particular'];
    $billBookArr[$a]['qty']         = $billRow['qty'];
    $billBookArr[$a]['labour']      = $billRow['labour'];
    $billBookArr[$a]['amount']      = $billRow['amount'];
    $a++;
  }
}

// This for select party : Start
$selectParty = "SELECT partyId,partyName 
                  FROM party
                 ORDER BY partyName DESC";
$selectPartyRes = mysql_query($selectParty);
$a = 0;
$party['partyId'][$a]   = 0;
$party['partyName'][$a] = "Select";
$a++;
while($partyRow = mysql_fetch_assoc($selectPartyRes))
{
  $party['partyId'][$a]   = $partyRow['partyId'];
  $party['partyName'][$a] = $partyRow['partyName'];
  $a++;
}
// This for select party : End

  // This for select billBook No. : Start
  $selectBillNo = "SELECT billNo FROM billbook
                 ORDER BY billBookId DESC";
  $selectBillNoRes = mysql_query($selectBillNo);
  if($billNoRow = mysql_fetch_assoc($selectBillNoRes))
    if($billNoRow['billNo'] == 100)
      $billBookNo = 1;
    else
      $billBookNo = $billNoRow['billNo'] + 1;
  // This for select billBook No. : End
  

//echo "Last : ".$billBookId."<br>";
$smarty = new smarty;
require("bottom.php");

$smarty->assign("l_partySelect",$l_partySelect);
$smarty->assign("l_billBookDate",$l_billBookDate);
$smarty->assign("l_particulars",$l_particulars);
$smarty->assign("l_weight",$l_weight);
$smarty->assign("l_pari",$l_pari);
$smarty->assign("l_netWeight",$l_netWeight);
$smarty->assign("l_touch",$l_touch);
$smarty->assign("l_waste",$l_waste);
$smarty->assign("l_fine",$l_fine);
$smarty->assign("l_qty",$l_qty);
$smarty->assign("l_labour",$l_labour);
$smarty->assign("l_amount",$l_amount);
$smarty->assign("l_add",$l_add);
$smarty->assign("l_remove",$l_remove);
$smarty->assign("l_addBillBook",$l_addBillBook);
$smarty->assign("l_billBook",$l_billBook);
$smarty->assign("l_total",$l_total);
$smarty->assign("l_billBookDetailId",$l_billBookDetailId);
$smarty->assign("l_save",$l_save);
$smarty->assign("party",$party);
$smarty->assign("billBookNo",$billBookNo);
$smarty->assign("msg",$msg);
$smarty->assign("isEdit",$isEdit);
$smarty->assign("partyId",$partyId);
$smarty->assign("billDate",$billDate);
$smarty->assign("billBookArr",$billBookArr);
$smarty->assign("billBookId",$billBookId);
$smarty->display("billBookAdd.tpl");
?>